
import os
import xlsxwriter
def write2Excel(data,path):
    if len(data)==0:
        print("data empty")
        return
    path=path[0:-4]+'.xlsx'
    workbook = xlsxwriter.Workbook(path)
    worksheet = workbook.add_worksheet('sheet1')
    datalist=data.split('\n')
    line=0
    if len(datalist)>0:
        for frame in datalist:
            framelist=frame.split(' ')
            for i in range(len(framelist)):
                worksheet.write(line,i, framelist[i])
            line=line+1

    #worksheet.save(path)
    workbook.close()
    print('saved:'+path)
def print2TXT(data,path):
    path=path[0:-4]+'condata.TXT'
    with open(path,'w') as file:
        file.write(data)
def convertTXT(path):
    if path[-3:]=='TXT' or path[-3:]=='txt':
        pass
    else:
        data=''
        print("不是文本文档")
        return data
    with open(path,'r') as file:
        s=file.readline()
        data=''
        firstline=True
        while s!='':
            if len(s)>15:
                if s[14]!='收':
                    s = file.readline()
                    continue
                st=s
                st = st[17:-1]#去除时间戳
                if st[0:23]=='02 01 04 03 06 05 08 07':#帧头匹配
                    if firstline:
                        data = data + st#第一行不加换行
                        firstline=False
                    else:
                        data=data+'\n'+st
                else:
                    data=data+st
            s=file.readline()
        return data
def readDir(dirPath):
    if dirPath[-1] == '/':
        return
    allFiles = []
    if os.path.isdir(dirPath):
        fileList = os.listdir(dirPath)
        for f in fileList:
            f = dirPath + '\\' + f
            if os.path.isdir(f):
                subFiles = readDir(f)
                allFiles = subFiles + allFiles  # 合并当前目录与子目录的所有文件路径
            else:
                allFiles.append(f)
        return allFiles
    else:
        return allFiles
allfile=readDir('D:\\Code\\covertTXT2data_excel\\TXTdata')
for path in allfile:
    data=convertTXT(path)
    #print2TXT(data, path)
    write2Excel(data, path)
print('end converting')